import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
// createRouter 用于创建vueRouter实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // 指定路由模式为history
  routes: [
    { path: '/login', name: 'login', component: () => import('@/views/login/LoginPage.vue') },
    {
      path: '/',
      name: 'layout',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          name: '/article/manage',
          component: () => import('@/views/article/ArticleManage.vue')
        },
        {
          path: '/article/channel',
          name: '/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue')
        },
        {
          path: '/user/profile',
          name: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/avatar',
          name: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        },
        {
          path: '/user/password',
          name: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        }
      ]
    }
  ]
})
/*
  return undefined true 直接放行
  return false 返回from页面
  return 具体的路径对象 '/login' {name:'login'} 拦截到对应的路径页面


 */
router.beforeEach((to) => {
  // 若无token，是否访问非登录页，则拦截到登录页，其他放行
  const userStore = useUserStore()
  // console.log('token', userStore.token)
  // console.log('path', to)
  if (!userStore.token && to.path !== '/login') {
    return '/login'
  } else {
    return true
  }
})
export default router
// import.meta.env.BASE_URL 这是vite中暴露的环境变量 就是vite.config.js文件中的 base 属性配置项
